<?php

	session_start();
include_once '../pushing.php';

if ($pushTime == true) {
	if ($_SESSION['UserId'] != 3)
		header('Location: push.php');
}
	
	if(!isset($_SESSION['UserId']))
	{
		header('Location: login.php');
   		die();
	}
	
	include_once '../Functions/generateQuestions.php';
	require_once '../mysqlConnect.php'; //mysqli database connect
	
	
	$conn = GetConnection();
	$sql = "SELECT * FROM physical_symptom_questions ORDER BY qnumber";
	$result = $conn->query($sql);
	$physical_symptom_questions = array();
	
	while ($row = $result->fetch_assoc()) {
		$physical_symptom_questions[] = $row;
	}
	
	//generate all question HTML
	$HTML = generateQuestions($physical_symptom_questions);
	

	
	function getSectionInfobyID ($id)
	{
		$conn = GetConnection();
		$sql = "SELECT * FROM Section S WHERE S.ID = '$id'";
		$value = $conn->query($sql);
		$rs = $value->fetch_assoc();
		return $rs;	
		$conn->close();
	}
	function getPatientInfobyID($id)
	{
		$conn = GetConnection();
		$sql = "SELECT * FROM Patient WHERE ID ='$id'";
		$value = $conn->query($sql);
		$rs = $value->fetch_assoc();
		return $rs;	
		$conn->close();
	}

	function uploadSymptoms ($HTML) {
		
		$conn = GetConnection();
		$answers = array();
		$answers[] = '';
		for ($i = 0 ; $i < count($HTML); $i++)
			$answers[] = $_POST[$HTML[$i][0]['answerName']];
		
		$sql = "INSERT INTO physical_symptom_answers " . 
		"(patient_id, qnumber1, qnumber2, qnumber3, qnumber4, qnumber5, qnumber6, qnumber7, qnumber8, qnumber9, qnumber10, qnumber11, qnumber12, qnumber13, " . 
		"qnumber14, qnumber15, qnumber16, qnumber17, record_date) VALUES " . 
		"('" . $_GET['PatId'] . "', " . 
		"'$answers[1]', '$answers[2]', '$answers[3]', '$answers[4]', '$answers[5]', '$answers[6]', '$answers[7]', '$answers[8]', '$answers[9]', '$answers[10]', " . 
		"'$answers[11]', '$answers[12]', '$answers[13]', '$answers[14]', '$answers[15]', '$answers[16]', '$answers[17]', '$answers[18]')";


		$conn->query($sql);
		if ($conn->error)
			return $conn->error;
		else
			return true;
		
		/*TODO - make this dynamic - if she adds more questions into the database, the upload function should still work
		for ($i = 0; $i < count($HTML); $i++) {
			$answers[] = $_POST[$HTML[$i][0]['answerName']];
			$answerNum = end(explode("_", $HTML[$i][0]['answerName']));
			print_r(substr($answerNum, 3));
			
			if ($i == count($HTML) - 1) 
				$sql .= ", ";
			else
				$sql .= "";
		}
		*/
			
		$conn->close();

	}
	
	$SectionInfo = getSectionInfobyID (2);
	$patientInfo = getPatientInfobyID($_REQUEST['PatId']);
	
	
if (isset($_REQUEST['isPostBack'])) //if the user has reloaded the page using the submit button
{

	$ValidationErrors = array();

	//automated error checker
	foreach ($HTML as $key => $value) {
		
		if (isset($_POST[$value[0]['answerName']])) {
			
			$ans = $_POST[$value[0]['answerName']];
			
			switch($value[0]['type']) {
				
				case 1: //drop down menu
					if ($ans == 9999) {
						$ValidationErrors[] = array("textId" => $value[0]['textId']);
					}
					break;
				case 2://text input
					if ($ans == '' || $ans == null) {
						$ValidationErrors[] = array("textId" => $value[0]['textId']);
					}
					break;
				case 3://date input
					if ($ans == '' || $ans == null) {
						$ValidationErrors[] = array("textId" => $value[0]['textId']);
					}
					break;
				case 4://medication drop down
					if ($ans == 9999) {
						$ValidationErrors[] = array("textId" => $value[0]['textId']);
					}
					break;
				case 5://test drop down
					if ($ans == 9999) {
						$ValidationErrors[] = array("textId" => $value[0]['textId']);
					}
					break;
			}
		}
	}
		
		
	
	if (!(count($ValidationErrors) > 0)) {
		
		$upload = uploadSymptoms($HTML);	
				
		if (!$upload == true) {
			echo '<script language="javascript" type="text/javascript">
			alert("Coult NOT Upload Physical Symptoms for Patient ' . $patientInfo['PatID'] . ': Database Query Error: '. $upload . '");
			redirect();
			function redirect(){
				window.location.href = "Physical Symptoms.php?PatId=' . $_GET['PatId'] . '";
			}
			</script>';
		} else {
			echo '<script language="javascript" type="text/javascript">
			alert("Symptoms for Patient ' . $patientInfo['PatID'] . ' Successfully Added to Database");
			redirect();
			function redirect(){
				window.location.href = "Physical Symptoms.php?PatId=' . $_GET['PatId'] . '";
			}
			</script>';
		}
	}
}
	
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>Physical Test</title>
	<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
	<script src="../JavaScript/jQueryTabs/js/jquery-1.6.2.min.js" type="text/javascript"></script>
	<script src="../JavaScript/jQueryTabs/js/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>
	<link rel="stylesheet" type="text/css" href="../JavaScript/jQueryTabs/css/custom-theme/jquery-ui-1.8.16.custom.css"/>
	<script type="text/javascript">
		$(document).ready(function() {

			<?php if (isset($ValidationErrors)) { 
					if (count($ValidationErrors) > 0 ) {
						foreach ($ValidationErrors as $key => $value) { ?>
							$("#<?php echo $value['textId'];?>").css('color', 'red');
						<?php } 
					}
				}?>
		});
		
	</script>
	<link rel="stylesheet" type="text/css" href="../Styler.css"/>
</head>

<body>
	<div id="header">
    	<div class="pageTitleText">Physical Symptoms</div>
    	<div class="pageTitleText" style="font-size: 1em;">
	        <span class="pageTitleSub">Patient: <?php echo $patientInfo['PatID'];?></span>
	        <span class="pageTitleSub">Date Diagnosed: <?php echo $patientInfo['DateDiagnosed'];?></span>
        </div>
 	</div>  
    
   
	<div id="mainMenu" style="height: 451px;">
    	<ul style="list-style: none outside none;">
	        
	        <li>
    			<a href="choosePatient.php?SID=2" style="font-weight: bold; color: #7C3709;">Choose New Patient</a>
    		</li>

	        <li>
	         	<a href="Add_ICD9.php?PatId=<?php echo $_GET['PatId'];?>">Patient ICD9</a>
	        </li>
	        
	        <li>
	         	<a href="Add Prescription.php?PatId=<?php echo $_GET['PatId'];?>">Patient Prescription</a>
	        </li>
	        
	        <li>
	        	<a href="Physical Symptoms.php?PatId=<?php echo $_GET['PatId'];?>"  style="font-weight: bold; color: #FB7D08;">Physical Symptoms</a>
	        </li>
	        
	        <li>
	        	<a href="Neuropsychological Symptoms.php?PatId=<?php echo $_GET['PatId'];?>">Neuropsychological Symptoms</a>
	        </li>
	        
	        <li>
	        	<a href="Psychological Test.php?PatId=<?php echo $_GET['PatId'];?>">Psychological Test</a> 
	        </li>
	        
	        <li>
	        	<a href="Diagnostic Test.php?PatId=<?php echo $_GET['PatId'];?>">Diagnostic Test</a>
	        </li>
	        
	        <li>
	        	<a href="viewPatient.php?PatId=<?php echo $_GET['PatId'];?>">View Patient Information</a>
	        </li>
	        
	        <li>
	         	<a href="Edit Patient.php?PatId=<?php echo $_GET['PatId'];?>">Edit Patient Information</a>
	        </li>
	        
	        <li>
	        	<a href="Save Information.php?PatId=<?php echo $_GET['PatId'];?>">Save Patient Information</a>
	        </li>
	        
	       <li style="border-bottom: 1px solid #FD9D45;">
	       	 	<del><!--<a href="query.php">-->Query<!--</a>--></del>
	        </li>
	        
	        <li>
	       	 	<a href="home.php">Home</a>
	        </li> 
	         
	        <li>
	       	 	<a href="logout.php">Logout</a>
	        </li>
        </ul>
    </div>  
     
    
    
    <?php if(isset($ValidationErrors)) { 

    	if (count($ValidationErrors) > 0) {?>
			
			<div class="noQueryResults">
			    <img src="../Images/error.png" style="float:left; margin: 5px 5px 5px 15px;"></img>
			    <p style="font-weight: bold; line-height: 1; margin: 5px 5px 5px 55px;">Error</p>
				<p style="line-height: 1; margin: 5px 5px 5px 55px;">		
		    	<?php if (count($ValidationErrors) > 1) { 
		    		echo 'Multiple Errors';
		    	} else { 
		    		echo 'Error';
		    	}?>
		    	</p>
			</div>
			
    <?php } }?>
   
   <div class="formContainer">     
        <form name="addPatientForm" method="post" action="<?php echo $_SERVER["PHP_SELF"].'?PatId='.$_REQUEST['PatId'] ?>">
	        <input type="hidden" name="isPostBack" value="true" />
	        
	        <div class="Questions" style="width: 925px;">
	                 
				 <?php 
				 $i = 0;
				 $limit1 = ceil(count($HTML)/3);
				 $limit2 = ceil(count($HTML)/3) * 2;
				 $limit3 = count($HTML); 
				 ?>
				 
		            	<div class="questionLeftColumn">
		                	<?php
		                	for ($i; $i < $limit1; $i++) {	
			                  	echo $HTML[$i][1];
		                	}
		                	?>
		            	</div>
		        
			            <div class="questionRightColumn">
							<?php 
							for ($i = $limit2; $i < $limit3; $i++) {	
			                   	echo $HTML[$i][1];
			                }?>
			            </div>

			            <div class="questionMiddleColumn">
			                <?php 
							for ($i = $limit1; $i < $limit2; $i++) {	
			                  	echo $HTML[$i][1];
		                	}?>
			            </div>
			            
	         </div>
	         
	         <input type="submit" value="Submit" class="loginButton" style="margin-top: 0px;"/>
         </form>
     </div>      
    
     
</body>
</html>